import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:oktoast/oktoast.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:screenshot/screenshot.dart';
import 'package:yysk_app/env/env.dart';
import 'package:yysk_app/model/user_friend/recommend_user_info_model.dart';
import 'package:yysk_app/model/user_friend/user_friend_list_model.dart';
import 'package:yysk_app/net/api/mall_url.dart';
import 'package:yysk_app/net/api/user_api.dart';
import 'package:yysk_app/net/http.dart';

class MyFriendPageController extends GetxController {
  late RxString labelName = '我的好友圈'.obs;
  final hotWordsList = RxList([]);
  final ScrollController scrollController = ScrollController();
  final total = RxInt(0);
  final totalReward = RxString('0');
  final needClose = RxBool(false);
  int pageNo = 1;
  int pageSize = 20;
  final friendList = RxList<UserFriendListItemModel>();
  final level = RxString('1');
  final showClose = false.obs;
  final Rx<Uint8List?> screenImg = Rx<Uint8List?>(null);
  ScreenshotController screenshotController = ScreenshotController();
  final env = Env.envConfig;

  @override
  void onInit() {
    super.onInit();
    // 热门搜索
    // getHotWords();
    getFriendListPage();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        getFriendListPage(loadMore: true);
      }
    });
  }

  getFriendListPage({loadMore = false}) {
    if (loadMore) {
      pageNo++;
    } else {
      pageNo = 1;
    }
    try {
      http.netFetch<UserFriendListModel>(
        UserApi.getFriendList,
        method: Method.post,
        params: {'pageNo': pageNo, 'pageSize': pageSize, 'level': level.value},
        success: (result) {
          List<UserFriendListItemModel> items = result.data?.list ?? [];
          if (loadMore && items.isEmpty) {
            pageNo--;
          }
          if (!loadMore) {
            friendList.clear();
          }
          friendList.addAll(items);
          total.value = result.data!.total!;
          getTotalReward();
        },
      );
    } catch (e) {
      if (loadMore) {
        pageNo--;
      }
    }
  }

  changeTab(String code) {
    if (code == level.value) {
      return;
    }
    level.value = code;
    getFriendListPage();
  }

  getHotWords() async {
    try {
      return await http.netFetch<dynamic>(
        '${MallUrl.getHotWords}?count=20',
        method: Method.get,
        success: (result) {
          hotWordsList.value = result.result;
        },
      );
    } catch (e) {
      return Future.error(e);
    }
  }

  getTotalReward() async {
    try {
      return await http.netFetch<dynamic>(
        UserApi.getTotalReward,
        method: Method.post,
        params: {'pageNo': pageNo, 'pageSize': pageSize, 'level': level.value},
        success: (result) {
          totalReward.value = result.data;
        },
      );
    } catch (e) {
      return Future.error(e);
    }
  }

  Future<void> saveScreenshot({Uint8List? imgBytes}) async {
    // showToast('点击');
    try {
      // 请求权限
      final PermissionState permission =
          await PhotoManager.requestPermissionExtend();

      if (!permission.isAuth) {
        showToast('保存失败：需要相册访问权限');
        return;
      }
      if (imgBytes == null) {
        showToast('制图中,请稍后点击保存');
        needClose.value = false;
        return;
      }

      // 保存到相册
      final AssetEntity? asset = await PhotoManager.editor.saveImage(
        imgBytes,
        filename:
            'Flutter_Screenshot_${DateTime.now().millisecondsSinceEpoch}.png',
      );

      if (asset != null) {
        showToast('保存成功');
        needClose.value = true;
      } else {
        // throw Exception('保存失败: ${result['errorMessage']}');
      }
    } catch (e) {
      showToast('保存失败');
    }
  }

  Future getMyInvitedInfo() async {
    try {
      return await http.netFetch<RecommendUserInfoModel>(
        UserApi.getRecommendUserInfo,
        method: Method.get,
        success: (result) {},
      );
    } catch (e) {
      return Future.error(e);
    }
  }

  @override
  void onClose() {
    super.onClose();
    Get.delete<ScrollController>(); //删除控制器实例
    scrollController.dispose();
  }
}
